const mongoose = require('mongoose');

const projectSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    maxlength: 200
  },
  protocolNumber: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  version: {
    type: String,
    default: '1.0.0'
  },
  versionDate: {
    type: Date,
    required: true,
    default: Date.now
  },
  status: {
    type: String,
    enum: ['active', 'completed', 'paused'],
    default: 'active'
  },
  description: {
    type: String,
    trim: true,
    maxlength: 1000
  },
  isTemplate: { type: Boolean, default: false }, // 新增字段，用于标识项目是否为模板
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  updatedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  configSections: [{
    sectionId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Section',
      required: true
    },
    order: {
      type: Number,
      required: true
    },
    config: {
      type: mongoose.Schema.Types.Mixed,
      default: {}  // 项目特定的配置覆盖
    }
  }],
  // 项目层前置页（导出在目录之前）
  frontMatter: [{
    formId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Form',
      required: true
    },
    order: { type: Number, default: 0 },
    showInToc: { type: Boolean, default: false },
    tocLevel: { type: Number, enum: [1, 2], default: 1 },
    customTitle: { type: String, trim: true, maxlength: 200 },
    pageBreakAfter: { type: Boolean, default: true },
    // 新增：不导出表单名称（隐藏表单标题）
    hideFormTitle: { type: Boolean, default: true }
  }],
  config: {
    documentTitle: String,
    watermark: String,
    pageSettings: {
      size: {
        type: String,
        enum: ['A4', 'A3', 'Letter'],
        default: 'A4'
      },
      orientation: {
        type: String,
        enum: ['portrait', 'landscape'],
        default: 'portrait'
      },
      margins: {
        top: { type: Number, default: 20 },
        bottom: { type: Number, default: 20 },
        left: { type: Number, default: 25 },
        right: { type: Number, default: 25 }
      }
    }
  }
}, {
  timestamps: { createdAt: 'createTime', updatedAt: 'updateTime' }
});

// 索引
projectSchema.index({ createdBy: 1, createTime: -1 });
projectSchema.index({ status: 1 });
projectSchema.index({ protocolNumber: 1 }, { unique: true });
projectSchema.index({ status: 1, createTime: -1 });
projectSchema.index({ createdBy: 1, status: 1, createTime: -1 });
projectSchema.index({ versionDate: -1 }); // 添加版本日期索引

module.exports = mongoose.model('Project', projectSchema);